<!DOCTYPE HTML>
<html>
    <head>
        <style>
            body {
                margin: 0px;
                padding: 0px;
            }
        </style>
        <meta http-equiv="Content-Language" content="fr" /> 
    </head>
    <body>
    <div id="container"></div>
    <script src="../scripts_js/kinetic-v4.5.1.js"></script>
    <script src="../scripts_js/XMLHttpRequest.js"></script>
    <script>

        function animate(im, x, y) {
            // update

            if (im.getX() < x)
            {
                im.setX(im.getX() + 1)
            }
            if (im.getX() > x)
            {
                im.setX(im.getX() - 1)
            }
            if (im.getY() < y)
            {
                im.setY(im.getY() + 1)
            }
            if (im.getY() > y)
            {
                im.setY(im.getY() - 1)
            }
            if (!(im.getX() > x - 1 && im.getX() < x + 1 && im.getY() > y - 1 && im.getY() < y + 1)) {
                animate(im, x, y);

            }

        }

        function loadImages(sources, music, callback) {
            var images = {};
            var loadedImages = 0;
            var numImages = 0;
            // get num of sources
            for (var src in sources) {
                numImages++;
            }
            for (var src in sources) {
                images[src] = new Image();
                images[src].onload = function() {
                    if (++loadedImages >= numImages) {
                        callback(images, music);
                    }
                };
                images[src].src = sources[src];
            }
        }

        function isNearOutline(im, outline) {

            var a = im;
            var o = outline;
            if (a.getX() > o.getX() - 80 && a.getX() < o.getX() + 80 && a.getY() > o.getY() - 80 && a.getY() < o.getY() + 80) {
                return true;
            }
            else {
                return false;
            }
        }
        function drawBackground(background, beachImg, text) {
            var canvas = background.getCanvas();
            var context = background.getContext();

            context.drawImage(beachImg, 1, 1, window.innerWidth, window.innerHeight);
            context.font = "20pt Calibri";
            context.textAlign = "center";
            context.fillStyle = "black";
            context.fillText(text, canvas.width / 2, 40);
        }

        function initStage(images, music) {
            var stage = new Kinetic.Stage({
                container: 'container',
                width: window.innerWidth - 10,
                height: window.innerHeight - 10
            });
            var imLayer = new Kinetic.Layer();
            var layer = new Kinetic.Layer();
            var xims = 65;
            var x2 = 65;
            var score = 0;
            var outlines = {};
            for (var key in images) {
                (function() {
                    if (!(key == "back_ground")) {
                        if (key.indexOf("_black") === -1) {
                            var audioElement = document.createElement('audio');
                            audioElement.setAttribute('src', '../sons/3672.mp3');
                            var im = new Kinetic.Image({
                                name: key,
                                image: images[key],
                                width: (window.innerWidth / 7),
                                height: (window.innerHeight / 5),
                                x: xims,
                                y: (window.innerHeight / 6),
                                draggable: true,
                                stroke: 'red',
                                strokeWidth: 10,
                                strokeEnabled: false
                            });
                            xims += im.getWidth() + (window.innerWidth / 14);
                            var x = im.getX();
                            var y = im.getY();


                            im.on("dragend", function() {
                                //alert(outlines[im.getName()+"_black"].getX() +" "+ outlines[im.getName()+"_black"].getY()+" "+ im.getName());
                                if (!outlines[im.getName() + "_black"].inRightPlace && isNearOutline(outlines[im.getName() + "_black"], im)) {

                                    im.setX(outlines[im.getName() + "_black"].getX());
                                    im.setY(outlines[im.getName() + "_black"].getY());

                                    imLayer.draw();
                                    // disable drag and drop
                                    im.setDraggable(false);
                                    im.inRightPlace = true;
                                    if (++score >= 4) {
                                        var text = "Felicitations :) !"
                                        var audioElement2 = document.createElement('audio');
                                        audioElement2.setAttribute('src', music[key]);
                                        audioElement2.play();
                                        drawBackground(layer, images.back_ground, text);
                                    }
                                }
                                else {
                                    animate(im, x, y);
                                }
                            });

                            im.on("dragstart", function() {
                                if (!im.inRightPlace) {
                                    var audioElement2 = document.createElement('audio');
                                    audioElement2.setAttribute('src', music[im.getName()]);
                                    audioElement2.setAttribute('preload', 'auto');
                                    audioElement2.play();
                                }
                            });

                            im.on("touchstart", function() {
                                if (!im.inRightPlace) {
                                    var audioElement2 = document.createElement('audio');
                                    audioElement2.setAttribute('src', music[im.getName()]);
                                    audioElement2.setAttribute('preload', 'auto');
                                    audioElement2.play();
                                }
                            });

                            imLayer.add(im);
                        }

                        else {
                            var car = new Kinetic.Image({
                                image: images[key],
                                x: x2,
                                y: (window.innerHeight / 2) + (window.innerHeight / 6),
                                width: (window.innerWidth / 7),
                                height: (window.innerHeight / 5),
                                draggable: false
                            });
                            x2 += car.getWidth() + (window.innerWidth / 14);
                            outlines[key] = car;
                            imLayer.add(car);

                        }
                    }
                })();

            }


            var text1 = "Placez les icones dans leurs places"
            stage.add(layer);
            drawBackground(layer, images.back_ground, text1);
            stage.add(imLayer);



            // use event delegation to update pointer style
            // and apply borders
            imLayer.on('mouseover', function(evt) {
                var shape = evt.shape;
                document.body.style.cursor = 'pointer';
                if (!shape.inRightPlace) {
                    shape.enableStroke();
                    imLayer.draw();
                }
            });
            imLayer.on('mouseout', function(evt) {
                var shape = evt.shape;
                document.body.style.cursor = 'default';
                shape.disableStroke();
                imLayer.draw();
            });
            imLayer.on('touchstart', function(evt) {
                var shape = evt.shape;
                document.body.style.cursor = 'pointer';
                if (!shape.inRightPlace) {
                    shape.enableStroke();
                    imLayer.draw();
                }
            });
            imLayer.on('touchend', function(evt) {
                var shape = evt.shape;
                document.body.style.cursor = 'default';
                shape.disableStroke();
                imLayer.draw();
            });


        }
        var sources = {
        };
        var music = {
        };

        var xmlhttp = getXMLHttpRequest();
        xmlhttp.open("GET", "../xml/image.xml", false);
        xmlhttp.send();
        xmlDoc = xmlhttp.responseXML;

        var racine = xmlDoc.documentElement;
        var tagnom = racine.getElementsByTagName('carre');
        var img = tagnom[0].getElementsByTagName('img');
        for (var i = 0; i < img.length; i++) {
            sources[img[i].getElementsByTagName('nom')[0].firstChild.nodeValue] = img[i].getElementsByTagName('src')[0].firstChild.nodeValue;
        }

        racine = xmlDoc.documentElement;
        tagnom = racine.getElementsByTagName('images');
        img = tagnom[0].getElementsByTagName('img');
        for (var i = 0; i < img.length; i++) {
            sources[img[i].getElementsByTagName('nom')[0].firstChild.nodeValue] = img[i].getElementsByTagName('src')[0].firstChild.nodeValue;
            music[img[i].getElementsByTagName('nom')[0].firstChild.nodeValue] = img[i].getElementsByTagName('sound')[0].firstChild.nodeValue;
        }
        racine = xmlDoc.documentElement;
        tagnom = racine.getElementsByTagName('back');
        img = tagnom[0].getElementsByTagName('img');
        for (var i = 0; i < img.length; i++) {
            sources[img[i].getElementsByTagName('nom')[0].firstChild.nodeValue] = img[i].getElementsByTagName('src')[0].firstChild.nodeValue;
             music[img[i].getElementsByTagName('nom')[0].firstChild.nodeValue] = img[i].getElementsByTagName('sound')[0].firstChild.nodeValue;
        }
        loadImages(sources, music, initStage);

    </script>
</body>
</html>
